package cn.itrip.trade.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.common.DtoUtil;
import cn.itrip.trade.service.OrderService;
import cn.itrip.trade.wx.WXPayConstants;
import cn.itrip.trade.wx.WXPayUtil;
import cn.itrip.trade.wx.WxPayRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/wxpay")
public class WxpaymentController {
    @Resource
    private OrderService  orderService;

    static Logger logger= Logger.getLogger(WxpaymentController.class);
    /**
     * 生成微信支付二维码
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "/createqccode/{orderNo}",method = RequestMethod.GET)
    @ResponseBody
   public Dto createCode(@PathVariable String orderNo){
        try {
            ItripHotelOrder  order =orderService.loadItriptHotelOrder(orderNo);
            //1.构造参数
            HashMap<String, String> data = new HashMap<String, String>();
            data.put("body", "爱旅行-预定房间");
            data.put("out_trade_no", orderNo);
            data.put("device_info", "");
            data.put("fee_type", "CNY");
            //传入订单金额 转成整数
            data.put("total_fee", order.getPayAmount().multiply(new BigDecimal(100)).toBigInteger().toString());
            data.put("spbill_create_ip", "123.12.12.123");
            //请求异步地址
            data.put("notify_url", "http://235065dv94.iok.la/wxpay/notify");
            data.put("trade_type", "NATIVE");
            data.put("product_id", "12");
            data.put("nonce_str", WXPayUtil.generateNonceStr());
            data.put("appid", "wxab8acb865bb1637e");
            data.put("mch_id", "11473623");
            data.put("sign_type", "HMAC-SHA256");
            //2.转成xml请求微信支付平台
            String reqXml = WXPayUtil.generateSignedXml(data, "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.HMACSHA256);
            //3.请求微信支付平台，获取预支付交易链接
            String resqxml = WxPayRequest.requestWx("https://api.mch.weixin.qq.com/pay/unifiedorder",reqXml);

            //3.获取code_url返回给前端
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resqxml);
            if (resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
                Map<String, String> result = new HashMap<>();
                result.put("codeUrl", resultMap.get("code_url"));
                return DtoUtil.returnDataSuccess(result);
            } else {
                return DtoUtil.returnFail(resultMap.get("return_msg"), "100002");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnSuccess("生成二维码失败");
        }


    }



    @RequestMapping("/notify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response){
        logger.info("notify 回调成功");
        //1.从request获取XML流  转换为MAP数据
        try {
            StringBuffer stringBuffer=new StringBuffer();
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            String temp;
            while ((temp=reader.readLine())!=null){
                stringBuffer.append(temp);
            }
            reader.close();
            inputStream.close();
            Map<String,String> resultMap=WXPayUtil.xmlToMap(stringBuffer.toString());
            boolean flag = WXPayUtil.isSignatureValid(resultMap, "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.HMACSHA256);
            if(flag){
                logger.info("签名验证成功");
                if(resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")){
                    String out_trade_no = resultMap.get("out_trade_no");
                    String trade_no = resultMap.get("prepay_id");
                    // 如果是未支付状态
                    if (!orderService.processed(out_trade_no)){
                        orderService.paySuccess(out_trade_no,2,trade_no);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Map<String,String> returnMap=new HashMap<>();
            returnMap.put("return_code","SUCCESS");
            returnMap.put("return_msg","OK");
            try {
                String respXml = WXPayUtil.generateSignedXml(returnMap,"2ab9071b06b9f739b950ddb41db2690d");
                response.getWriter().write(respXml);
                response.getWriter().flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping(value = "/queryorderstatus/{OrderNo}",method = RequestMethod.GET)
    @ResponseBody
    public Dto queryorderstatus(@PathVariable String OrderNo){
        try {
            ItripHotelOrder order = orderService.loadItriptHotelOrder(OrderNo);
            return  DtoUtil.returnSuccess(OrderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  DtoUtil.returnFail("查询失败","100003");
    }

}
